package io.summer.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author Moonlight
 */
@Configuration
@Slf4j
public class RedisConfig implements InitializingBean {
  @Autowired
  private RedisTemplate<Object, Object> redisTemplate;

  @Autowired
  private RedissonClient redissonClient;

  @Override
  public void afterPropertiesSet() throws Exception {
    // 使用Jackson2JsonRedisSerialize 替换默认序列化
    // default is JdkSerializationRedisSerializer
    RedisSerializer<?> jackson2JsonRedisSerializer = getRedisSerializer();
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.afterPropertiesSet();

    log.info("redissonClient codec: {}", redissonClient.getConfig().getCodec());
  }

  public static RedisSerializer<?> getRedisSerializer() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    return new GenericJackson2JsonRedisSerializer(objectMapper);
  }
}
